<template>
  <ul class="list">
    <li
      class="item"
      v-for="(item, key) in allCity"
      :key="key"
      :ref="key"
      @click="handleClick"
      @touchstart="handleTouchStart"
      @touchmove="handleTouchMove"
      @touchend="handleTouchEnd"
    >
      {{key}}
    </li>
  </ul>
</template>

<script>
export default {
  name: 'CityList',
  props: {
    allCity: Object
  },
  data () {
    return {
      touchFlag: false,
      startY: 0,
      timer: null
    }
  },
  computed: {
    alphabets () {
      var alphabets = []
      for (let i in this.allCity) {
        alphabets.push(i)
      }
      return alphabets
    }
  },
  updated () {
    this.startY = this.$refs['A'][0].offsetTop
  },
  methods: {
    handleClick (ev) {
      this.$emit('change', ev.target.innerText)
    },
    handleTouchStart () {
      this.touchFlag = true
    },
    handleTouchMove (ev) {
      if (this.touchFlag) {
        if (this.timer) {
          clearInterval(this.timer)
        }
        this.timer = setTimeout(() => {
          var touchY = ev.touches[0].clientY - 79
          var index = Math.floor((touchY - this.startY) / 20)
          // console.log(index)
          if (index >= 0 && index < this.alphabets.length) {
            this.$emit('change', this.alphabets[index])
          }
        }, 16)
      }
    },
    handleTouchEnd () {
      this.touchFlag = false
    }
  }
}
</script>

<style lang="stylus" scoped>
  @import '~styles/varibles.styl'
  .list
    display: flex
    flex-direction: column
    justify-content: center
    position: absolute
    top: 1.58rem
    right: 0
    bottom: 0
    width: 0.4rem
    .item
      text-align: center
      height: 0.4rem
      color: $bgColor
</style>
